﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using MySql.Data.MySqlClient;
using ZHDJ.Core;
using ZHDJ.Core.Util;

namespace ZHDJ.Data.BLL
{
    /// <summary>
    /// 党群待办
    /// </summary>
    public class PartyTaskHelper
    {
        /// <summary>
        /// 添加站务工作者待办
        /// </summary>
        /// <returns></returns>
        public static bool AddTaskToSysMamage(string relationId, string title, SysEnum.TaskCategory category, string fromUser,
            string taskUrl)
        {
            return AddTask(relationId, title, category, fromUser, new string[] {"SysMamage"}, taskUrl, SysEnum.TaskSpecie.SysMamage);
        }
        /// <summary>
        /// 添加个人待办
        /// </summary>
        /// <returns></returns>
        public static bool AddTaskToMember(string relationId, string title, SysEnum.TaskCategory category, string fromUser, string[] toUsers,
            string taskUrl)
        {
            return AddTask(relationId, title, category, fromUser, toUsers, taskUrl, SysEnum.TaskSpecie.Member);
        }

        /// <summary>
        /// 添加组织待办
        /// </summary>
        /// <returns></returns>
        public static bool AddTaskToBranch(string relationId, string title, SysEnum.TaskCategory category, string fromUser, string[] toUsers,
            string taskUrl,string source = "本组织")
        {
            return AddTask(relationId, title, category, fromUser, toUsers, taskUrl, SysEnum.TaskSpecie.Branch, source);
        }

        /// <summary>
        /// 添加待办
        /// </summary>
        /// <param name="relationId"></param>
        /// <param name="title"></param>
        /// <param name="category"></param>
        /// <param name="fromUser"></param>
        /// <param name="toUsers"></param>
        /// <param name="taskUrl"></param>
        /// <param name="taskSpecie"></param>
        /// <param name="source"></param>
        /// <returns></returns>
        private static bool AddTask(string relationId, string title, SysEnum.TaskCategory category, string fromUser, string[] toUsers,
            string taskUrl, SysEnum.TaskSpecie taskSpecie, string source = "本组织")
        {
            var para = new List<MySqlParameter>
            {
                new MySqlParameter() {DbType = DbType.String, ParameterName = "RelationID", Value = relationId},
                new MySqlParameter() {DbType = DbType.String, ParameterName = "Category", Value = category.ToString()},
                new MySqlParameter() {DbType = DbType.String, ParameterName = "TaskType", Value = "1"},
                new MySqlParameter() {DbType = DbType.String, ParameterName = "Title", Value = title},
                new MySqlParameter() {DbType = DbType.String, ParameterName = "FromUser", Value = fromUser},
                new MySqlParameter() {DbType = DbType.String, ParameterName = "Source", Value = source},
                new MySqlParameter(){DbType = DbType.String,ParameterName = "TaskSpecie",Value = taskSpecie.ToString()}
            };



            var sbSql = new StringBuilder();
            string strSql =
                @"INSERT INTO tblPartyTask (ID, RelationID, Category, TaskType, Title, FromUser, ToUser, TaskUrl, CreateTime,TaskSpecie,Source)
                                    VALUES (?TaskID{0}, ?RelationID, ?Category, ?TaskType, ?Title, ?FromUser, ?ToUser{0}, ?TaskUrl{0}, now(),?TaskSpecie, ?Source);";
            for (int i = 0; i < toUsers.Length; i++)
            {
                string taskID = StringHelper.NewID;
                string tmpTaskUrl = "";
                sbSql.AppendFormat(strSql, i);
                if (taskUrl.IndexOf("?") > 0)
                    tmpTaskUrl = taskUrl + "&TaskID=" + taskID;
                else
                    tmpTaskUrl = taskUrl + "?TaskID=" + taskID;

                para.Add(new MySqlParameter(){DbType = DbType.String,ParameterName = string.Format("ToUser{0}", i),Value = string.IsNullOrEmpty(toUsers[i]) ? "" : toUsers[i]});
                para.Add(new MySqlParameter(){DbType = DbType.String,ParameterName = string.Format("TaskID{0}", i),Value = taskID});
                para.Add(new MySqlParameter(){DbType = DbType.String,ParameterName = string.Format("TaskUrl{0}", i),Value = tmpTaskUrl});
                
               
            }
            if (sbSql.Length > 0)
            {

                return MySqlHelper.ExecuteNonQuery(sbSql.ToString(), para.ToArray()) > 0;
            }
            return false;
        }

        /// <summary>
        /// 任务变成已办
        /// </summary>
        /// <param name="relationID"></param>
        /// <param name="handler">处理人</param>
        /// <returns></returns>
        public static bool TaskDone(string relationID, string handler)
        {
            return UpdateTask(relationID, handler, "2");

        }

        /// <summary>
        /// 还原待办信息
        /// </summary>
        /// <param name="relationID">RelationID</param>
        /// <param name="handler">处理人</param>
        /// <returns></returns>
        public static bool ReductionTaskDone(string relationID, string handler)
        {
            return UpdateTask(relationID, handler, "1");
        }

        /// <summary>
        /// 取消待办
        /// </summary>
        /// <param name="relationID"></param>
        /// <param name="handler">处理人</param>
        /// <returns></returns>
        public static bool TaskCancel(string relationID, string handler)
        {
            return UpdateTask(relationID, handler, "3");
        }

        /// <summary>
        /// 更新待办状态
        /// </summary>
        /// <param name="relationID">RelationID</param>
        /// <param name="handler">处理人</param>
        /// <param name="taskType">待办状态</param>
        /// <returns></returns>
        public static bool UpdateTask(string relationID, string handler, string taskType)
        {
            var para = new List<MySqlParameter>
            {
                new MySqlParameter() {DbType = DbType.String, ParameterName = "RelationID", Value = relationID},
                new MySqlParameter() {DbType = DbType.String, ParameterName = "Handler", Value = handler},
                new MySqlParameter() {DbType = DbType.String, ParameterName = "TaskType", Value = taskType}
            };
            var sql =
                @"UPDATE  tblPartyTask SET TaskType =?TaskType,Handler = ?Handler, HandlerTime=now() WHERE RelationID = ?RelationID ;";
            return MySqlHelper.ExecuteNonQuery(sql, para.ToArray()) > 0;
        }

        /// <summary>
        /// 任务变成已办（根据用户）
        /// </summary>
        /// <param name="relationID">关联ID</param>
        /// <param name="toUser">接收人/组织</param>
        /// <param name="handler">处理人</param>
        /// <returns></returns>
        public static bool TaskDoneAndToUser(string relationID, string toUser, string handler)
        {
            var para = new List<MySqlParameter>
            {
                new MySqlParameter() {DbType = DbType.String, ParameterName = "RelationID", Value = relationID},
                new MySqlParameter() {DbType = DbType.String, ParameterName = "Handler", Value = handler},
                new MySqlParameter() {DbType = DbType.String, ParameterName = "ToUser", Value = toUser},
            };
            var sql =
                @"UPDATE dbo.tblPartyTask SET TaskType = '2',Handler = ?Handler, HandlerTime=now() WHERE RelationID = ?RelationID and ToUser = ?ToUser ;";
            return MySqlHelper.ExecuteNonQuery(sql, para.ToArray()) > 0;
        }

        /// <summary>
        /// 任务变成已办
        /// </summary>
        /// <param name="taskId">待办ID</param>
        /// <param name="handler">处理人</param>
        /// <returns></returns>
        public static bool TaskDoneByTaskId(string taskId, string handler)
        {
            var para = new List<MySqlParameter>
            {
                new MySqlParameter() {DbType = DbType.String, ParameterName = "TaskID", Value = taskId},
                new MySqlParameter() {DbType = DbType.String, ParameterName = "Handler", Value = handler},
            };
            var sql =
                @"UPDATE tblPartyTask SET TaskType = '2',Handler = ?Handler, HandlerTime=now() WHERE ID = ?TaskID;";
            return MySqlHelper.ExecuteNonQuery(sql, para.ToArray()) > 0;
        }

        /// <summary>
        /// 获取待办状态 
        /// </summary>
        /// <param name="relationID"></param>
        /// <returns></returns>
        public static string GetTaskType(string relationId)
        {

            var para = new List<MySqlParameter>
            {
                new MySqlParameter() {DbType = DbType.String, ParameterName = "RelationID", Value = relationId},
            };
            var sql =
                @"select TaskType from tblPartyTask where RelationID=@RelationID";
            var o = MySqlHelper.ExecuteScalar(sql, para.ToArray());
            return o != null && o != DBNull.Value ? o.ToString() : "";
        }


        /// <summary>
        /// 查找所有收到待办的人
        /// </summary>
        /// <param name="RelationID"></param>
        /// <param name="TaskType"></param>
        /// <returns></returns>
        public static Dictionary<string, string> GetToUser(string RelationID,string TaskType="")
        {
            var para = new List<MySqlParameter>
            {
                new MySqlParameter() {DbType = DbType.String, ParameterName = "RelationID", Value = RelationID},

            };
            
            var sql =
                @"select LoginID,UserName from tblPartyTask as a left join tblPartyOrgMembers as b on ( a.ToUser=b.LoginID)
 where  RelationID=?RelationID ";
            if (!string.IsNullOrEmpty(TaskType))
            {
                sql += " and TaskType=?TaskType ";
                para.Add(new MySqlParameter() { DbType = DbType.String, ParameterName = "TaskType", Value = TaskType });
            }
            var dt = MySqlHelper.ExecuteDataTable(sql, para.ToArray());
            return dt.Rows.Cast<DataRow>().ToDictionary(dr => dr["LoginID"].ToString(), dr => dr["UserName"].ToString());
        }


      
    }
}
